<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>活动列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card ref="card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            clearable=""
            v-model="queryInfo.query"
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button
            type="primary"
            @click="dialogVisible = true"
          >添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table
        :data="userList"
        style="width: 100%"
        border
        stripe
      >
        <el-table-column
          type="index"
          width="50"
        >
        </el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          width="120"
        >
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          width="180"
        >
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="电话"
          width="166"
        >
        </el-table-column>
        <el-table-column
          prop="role_name"
          label="角色"
          width="150"
        >
        </el-table-column>
        <el-table-column
          prop="mg_state"
          label="状态"
          width="150"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="upUser(scope.row)"
            >
            </el-switch>

          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          width="180"
        >
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showModification(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-star-off"
                size="mini"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页功能 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close="addClosed"
    >
      <!-- 内容区域 -->
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
      >
        <el-form-item
          label="用户名"
          prop="username"
        >
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
        >
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item
          label="邮箱"
          prop="email"
        >
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="mobile"
        >
          <el-input v-model="ruleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮区域 -->
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="addUser"
        >确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="upDialogVisible"
      width="50%"
      @close="editFormRef1"
    >
      <!-- 内容区域 -->
      <el-form
        :model="editForm"
        :rules="modification"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item
          label="用户名"
        >
          <el-input v-model="editForm.username" :disabled="true"></el-input>
        </el-form-item>

        <el-form-item
          label="邮箱"
          prop="email"
        >
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="mobile"
        >
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="upDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="editUserInfo"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var emailRule = (rule, value, cd) => {
      const regEmail = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
      if (regEmail.test(value)) {
        cd();
      }
      return cd(new Error("请输入正确的邮箱"));
    };
    var mobileRule = (rule, value, cd) => {
      const regmobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regmobile.test(value)) {
        cd();
      }
      return cd(new Error("请输入正确的手机号"));
    };
    return {
      // 需要传的参数
      queryInfo: {
        query: "",
        // 当前页
        pagenum: 1,
        // 每页显示2条
        pagesize: 2
      },
      // 总条数
      total: 0,
      //   保存获取来的数据
      userList: [],
      dialogVisible: false,
      ruleForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      ruleModification:{
        username: "",
        email: "",
        mobile: ""
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 6, message: "长度在 3 到 6 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 10, message: "长度在 6 到 10 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: emailRule, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: mobileRule, trigger: "blur" }
        ]
      },
      upDialogVisible: false,
      modification: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: emailRule, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: mobileRule, trigger: "blur" }
        ]
      },
      editForm : {}
      
    };
  },
  // 生命周期 获取用户列表数据
  created() {
    this.getUserList();
  },
  methods: {
    // 向后台发送请求获取用户列表数据
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo
      });
      // console.log(res);
      if (res.meta.status != 200) {
        return this.$message.error("获取用户列表失败！");
      }
      this.userList = res.data.users;
      this.total = res.data.total;
    },
    // 监听pagesize改变事件
    handleSizeChange(newSize) {
      // console.log(newSize);
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    // 监听页码值改变事件
    handleCurrentChange(current) {
      // console.log(current);
      this.queryInfo.pagenum = current;
      this.getUserList();
    },
    // 更改用户开关状态
    async upUser(ggkg) {
      //   console.log(ggkg);
      const { data: res } = await this.$http.put(
        `users/${ggkg.id}/state/${ggkg.mg_state}`
      );
      //   console.log(res);
      if (res.meta.status != 200) {
        ggkg.mg_state = !ggkg.mg_state;
        return this.$message.error("更改用户状态失败");
      }
      this.$message.success("更改用户状态成功！");
    },
    // 重置清空对话框
    addClosed() {
      // console.log(this.$refs.ruleForm);
      this.$refs.ruleForm.resetFields();
    },
    // 发送添加用户的请求
    async addUser() {
      let { data: res } = await this.$http.post("users", this.ruleForm);
      console.log(res);
      if (res.meta.status != 201) return this.$message.success(res.meta.msg);
      this.$message.success("添加用户成功");
      this.dialogVisible = false;
      this.getUserList();
    },
    // 修改用户信息对话框显示隐藏
    async showModification(id){
        this.upDialogVisible = true
        const {data:res} = await this.$http.get('users/'+id)
        if(res.meta.status !=200){
          return this.$message.error('更改用户信息失败')
        }
        this.editForm = res.data
      },
      // 修改对话框重置
      editFormRef1(){
        this.$refs.editFormRef.resetFields()
      },
      // 验证修改表单并提交
      editUserInfo(){
        this.$refs.editFormRef.validate(async valid=>{
          console.log(valid);
          if(!valid) return
          // 发送修改用户信息的数据请求
          const {data:res} = await this.$http.put('users/'+this.editForm.id,{
            email:this.editForm.email,
            mobile:this.editForm.mobile
          })
          if(res.meta.status != 200){
            return this.$message.error('修改用户信息失败！')
           
          }
           // 关闭对话框
             this.upDialogVisible = false;
            // 刷新数据列表
            this.getUserList()
            // 提示修改成功
            this.$message.success('修改用户信息成功！')
           
        })
      },
      // 删除功能弹框
      async deleteUser(id){
          console.log(id);
           const resule = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err);
        console.log(resule);
        if(resule != 'confirm'){
          return this.$message.info('已取消删除该用户')
        }
        const {data:res} = await this.$http.delete('users/'+id)
        if(res.meta.status != 200){
          return this.$message.error('删除用户失败！')
        }
        this.$message.success('删除用户成功')
        this.getUserList();
      }
  }
};
</script>

<style lang="less" scope>
</style>